package com.simga.library.http;

import com.orhanobut.hawk.Hawk;
import com.simga.library.utils.HawkKey;
import com.simga.library.utils.LogUtil;
import java.io.IOException;
import java.nio.charset.Charset;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

public class VerifyInterceptor implements Interceptor {

    private String versionName;

    private static final Charset UTF8 = Charset.forName("UTF-8");

    VerifyInterceptor(String versionName) {
        this.versionName = versionName;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        RequestBody requestBody = request.body();
        String sessionId;
        if (request.url().toString().contains("shop")) {
            sessionId = Hawk.get(HawkKey.SHOP_AUTHENTICATION, "");
        } else {
            sessionId = Hawk.get(HawkKey.USER_AUTHENTICATION, "");
        }
        Request.Builder builder = request.newBuilder();
        if (!request.url().toString().contains("getPhoneCode")) {
            builder.addHeader("sessionId", sessionId);
        }
        builder.addHeader("sessionId", sessionId);
        builder.url(request.url());
        request = builder.build();
        String requestMessage;
        requestMessage = request.method() + ' ' + request.url();
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            requestMessage += "?\n" + buffer.readString(UTF8);
        }
        LogUtil.e("sessionId", request.headers().get("sessionId"));
        LogUtil.e("RequestUrl", requestMessage);
        return chain.proceed(request);
    }
}
